/*
 * loader - consists of functions to test and load the requested url
 *
 * Copyright (c) 2008 Varun Kumar Reddy Dodla
 * Licensed under GPL (GPL-LICENSE.txt)
 *
 * $Date: 2008-10-16 
 */

//default url to load
var urlRequested = 'intro.html';


function getUrl(sUrl) {
	urlRequested = sUrl;
	Ext.MessageBox.wait( 'Loading the url...', 'Please wait', {interval: 200});
	
	//test the url
	log.message('--------------------------------------------');
	log.info('Attempting to test the Url: '+sUrl);
	try {
	$.ajax({
	   type: "GET",
	   url: sUrl,
	   dataType: 'html',
	   success: gotUrl,
	   error: getUrlError		   
	 });
	}catch(e) {
		log.error('An Exception occurred. Name: '+e.name);
		showErrorBox('Exception', 'There was an exception while trying to load the url:<br/><b>' + e.name + ' - ' + e.message+'</b>');

	   //this exceptions occurs when running locally
	   //so proceed even if it occurs
	   if(e.name == 'NS_ERROR_DOM_BAD_URI') {
	       Ext.MessageBox.wait( 'Loading the url...', 'Please wait', {interval: 200});
	       log.message('Known exception occurred. Ignoring and loading Url.');
	       loadUrl();    
	   }
	}

}

function gotUrl(data, textStatus) {
	//do the ajax stuff here
	log.info('Test successful. Loading Url.');
	loadUrl();
}

function loadUrl() {
	try {
		$('#center-iframe').contents()[0].location = "loader.jsp?url="+urlRequested;
	} catch(e) {
		showErrorBox('Error', 'Cannot load URL. Going back in history. Please try again.');
		history.go(-1);
	}
	
}

function reloadURL(noOfTimes) {
	window.frames[0].location = "loader.jsp?url="+urlRequested+"&reload=true";
	window.setTimeout(reloadCheck, 25000, noOfTimes++);
}

function reloadCheck(noOfTimes) {
	
	//noOfTimes can be used to stop reloading
	//NOT USED CURRENTLY SO MAY RESULT IN AN INFINITE RELOADING LOOP
	//A VERY VERY REMOTE CHANCE OF THAT HAPPENING
	
	//check access to the frame DOM
	try {
		var frameDoc = window.frames[0].document;
	}catch(e) {
		log.info("Cannot access frame DOM.");
		reloadURL();
	}
}

function getUrlError(XMLHttpRequest, textStatus, errorThrown) {
		log.error('Error while testing Url. Status: '+XMLHttpRequest.status);
		showErrorBox('Error', 'The following error was returned while trying to load the url:<br/>' +
          		 XMLHttpRequest.status + " - " +XMLHttpRequest.statusText);
	   loadUrl='intro.html';
	}

function urlLoaded() {
	if(detectForms()) {
		
		//clone the DOM object
		var iframeDoc = $('#center-iframe').contents()[0];
		var iframeDocClone = $('body', iframeDoc).clone(true);
		
		urlDOMClone = new DOMClone(iframeDocClone);
		
		dependencies = new Array();
	}
}
